<template>
  <el-dialog
    :title="showTitle"
    :visible.sync="showDialog"
    :close-on-click-modal="false"
    width="45%"
  >
    <el-form
      :model="formData"
      ref="refForm"
      label-position="right"
      label-width="110px"
    >
      <el-form-item
        label="优惠券名称："
        prop="tag_mid_table"
        :rules="[{ required: true, message: '请输入优惠券名称' }]"
      >
        <el-input
          v-model="formData.tag_mid_table"
          placeholder="请输入优惠券名称"
          maxlength="32"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="频度："
        prop="mid_table_remark_002"
        :rules="[{ required: true, message: '请选择频度' }]"
      >
        <el-select
          v-model="formData.mid_table_remark_002"
          style="width: 100%"
          placeholder="请选择频度"
        >
          <el-option label="每天一次" value="1"></el-option>
          <el-option label="仅仅一次" value="365000"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="有效时间段："
        prop="time_4_begin_end"
        :rules="[{ required: true, message: '请选择有效时间段' }]"
      >
        <el-date-picker
          v-model="formData.time_4_begin_end"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="优惠券类型："
        prop="mid_table_remark_033"
        :rules="[{ required: true, message: '请选择优惠券类型' }]"
      >
        <el-select
          v-model="formData.mid_table_remark_033"
          style="width: 100%"
          placeholder="请选择优惠券类型"
        >
          <el-option label="满减" value="101"></el-option>
          <el-option label="打折" value="102"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="formData.mid_table_remark_033 == 101"
        label="满减金额："
        prop="mid_table_remark_016"
        :rules="[
          {
            required: true,
            message: '请输入满减信息',
            validator: customValidateFeeTime,
          },
        ]"
      >
        <!-- <div class="wrap-manjian"></div> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="满" label-width="30px">
              <el-input
                v-model="formData.mid_table_remark_016"
                @input="
                  bindInputIntData(formData, 'mid_table_remark_016', true)
                "
                maxlength="13"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="减" label-width="30px">
              <el-input
                v-model="formData.mid_table_remark_017"
                @input="
                  bindInputIntData(formData, 'mid_table_remark_017', true)
                "
                maxlength="13"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        v-else
        label="优惠折扣："
        prop="mid_table_remark_017"
        :rules="[{ required: true, message: '请输入或选择折扣' }]"
      >
        <el-input-number
          v-model="formData.mid_table_remark_017"
          :precision="2"
          :step="0.01"
          :max="9.99"
          :min="1"
          placeholder="请输入或选择折扣"
        ></el-input-number>
      </el-form-item>
      <el-form-item
        v-if="showChooseCourse"
        label="特定课程："
        prop="tmp_mid_table_remark_046_047"
        :rules="[{ required: true, message: '请选择特定课程' }]"
      >
        <el-select
          v-model="formData.tmp_mid_table_remark_046_047"
          style="width: 100%"
          placeholder="请选择特定课程"
        >
          <el-option
            v-for="(item, idx) in courseList"
            :key="idx"
            :label="item.goods_name"
            :value="item.id_public_goods_info + ''"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showDialog = false">关闭</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { inputIntData, parseTime } from "@/utils/index";
import { middleList, courseMiddleList } from "@/api/middle";
export default {
  name: "CompCouponConfigCourse",
  props: {
    showTitle: {
      type: String,
      default: "新增/编辑",
    },
    showChooseCourse: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showDialog: false,
      formData: {
        id_public_middle_table: "",
        tag_mid_table: "",
        mid_table_remark_002: "",
        time_4_begin_end: [],
        mid_table_remark_033: "",
        mid_table_remark_016: "",
        mid_table_remark_017: "",
        // 选择的课程Id
        mid_table_remark_011: "",
        mid_table_remark_046: "",
        mid_table_remark_047: "",
        tmp_mid_table_remark_046_047: "",
      },
      isRequesting: false,
      courseList: [],
    };
  },

  methods: {
    async onEditOrAdd(row, course) {
      console.log(row, course);
      let courseList = [
        { id_public_goods_info: "-1", goods_name: "所有课程可用" },
      ];
      if (this.showChooseCourse) {
        let resCouseList = await this.getCourseList();
        courseList = courseList.concat(resCouseList);
      } else {
        courseList = courseList.concat(course);
      }
      this.courseList = courseList;
      let tmpData = {
        id_public_middle_table: "",
        tag_mid_table: "",
        mid_table_remark_002: "",
        time_4_begin_end: [],
        mid_table_remark_033: "",
        mid_table_remark_016: "",
        mid_table_remark_017: "",
        mid_table_remark_011: "",
        mid_table_remark_046: "",
        mid_table_remark_047: "",
        tmp_mid_table_remark_046_047: "",
      };
      if (row) {
        tmpData.id_public_middle_table = row.id_public_middle_table;
        tmpData.tag_mid_table = row.tag_mid_table;
        tmpData.mid_table_remark_002 = row.mid_table_remark_002;
        tmpData.time_4_begin_end = [row.time_4_begin, row.time_4_end];
        tmpData.mid_table_remark_033 = row.mid_table_remark_033;
        tmpData.mid_table_remark_016 = row.mid_table_remark_016;
        tmpData.mid_table_remark_017 = row.mid_table_remark_017;
        tmpData.mid_table_remark_047 = row.mid_table_remark_047;
        tmpData.mid_table_remark_046 = row.mid_table_remark_046;
        if (row.mid_table_remark_047 == 101) {
          row.mid_table_remark_046 = "";
          row.mid_table_remark_011 = "";
          tmpData.tmp_mid_table_remark_046_047 = "-1";
        }
        if (row.mid_table_remark_047 == 102) {
          tmpData.mid_table_remark_011 = row.mid_table_remark_011;
          tmpData.tmp_mid_table_remark_046_047 = row.mid_table_remark_011;
        }
      } else {
        if (!this.showChooseCourse) {
          tmpData.mid_table_remark_047 = 102;
          tmpData.mid_table_remark_011 = course.id_public_goods_info;
          //    mid_table_remark_011: "",
          // mid_table_remark_046: "",
          tmpData.tmp_mid_table_remark_046_047 = course.id_public_goods_info;
        }
      }
      this.formData = tmpData;
      console.log(this.formData, ">>>>>>>>>>");
      this.showDialog = true;
      this.$nextTick(() => {
        this.$refs.refForm.clearValidate();
      });
    },

    bindInputIntData(form, prop, notset) {
      let _this;
      if (!form) {
        _this = this;
      } else {
        if (notset) {
          _this = form;
        } else {
          _this = this[form];
        }
      }
      let val = _this[prop];
      val = inputIntData(val);
      _this[prop] = val;
    },
    customValidateFeeTime(rule, value, callback) {
      if (
        !this.formData ||
        (!this.formData.mid_table_remark_016 &&
          this.formData.mid_table_remark_016 !== 0) ||
        (!this.formData.mid_table_remark_017 &&
          this.formData.mid_table_remark_017 !== 0)
      ) {
        callback(new Error("请输入满减信息"));
        return;
      }
      callback();
    },
    handleSubmit() {
      this.$refs.refForm.validate((valid) => {
        if (valid) {
          this.onSubmit();
        }
      });
    },

    onSubmit() {
      if (this.isRequesting) {
        return;
      }
      this.isRequesting = true;
      let pre_db_para_id_public_middle_table =
        this.formData.id_public_middle_table || "";
      let tmp_mid_table_remark_046_047 = "";
      for (let i = 0; i < this.courseList.length; i++) {
        const element = this.courseList[i];
        if (
          element.id_public_goods_info ==
          this.formData.tmp_mid_table_remark_046_047
        ) {
          tmp_mid_table_remark_046_047 = element.goods_name;
          break;
        }
      }
      let dtNow = new Date();
      let postData = {
        invoke_method: "public_insert_or_update_middle_table",
        pre_db_para_middle_table_name:
          "public_middle_table_system_use_order_relate_rule_and_record",
        mid_table_remark_002: this.formData.mid_table_remark_002,
        tag_mid_table: this.formData.tag_mid_table,
        mid_table_remark_033: this.formData.mid_table_remark_033,
        mid_table_remark_014:-1,
        mid_table_remark_015:-1,
        mid_table_remark_016: this.formData.mid_table_remark_016,
        mid_table_remark_017: this.formData.mid_table_remark_017,
        mid_table_remark_011:
          this.formData.tmp_mid_table_remark_046_047 == -1
            ? ""
            : this.formData.tmp_mid_table_remark_046_047,
        mid_table_remark_046:
          this.formData.tmp_mid_table_remark_046_047 == -1
            ? ""
            : tmp_mid_table_remark_046_047,
        mid_table_remark_047:
          this.formData.tmp_mid_table_remark_046_047 == -1 ? 101 : 102,
        time_4_begin: parseTime(
          this.formData.time_4_begin_end[0],
          "{y}-{m}-{d} {h}:{i}:{s}"
        ),
        time_4_end: parseTime(
          this.formData.time_4_begin_end[1],
          "{y}-{m}-{d} {h}:{i}:{s}"
        ),
        type_middle_app: 10001,
        type_inner_app: 1001,
        is_online: 0,
      };
      if (!pre_db_para_id_public_middle_table) {

        Object.assign(postData, {
          mid_table_remark_007: parseTime(dtNow, "{y}{m}{d}"),
          mid_table_remark_006: parseTime(dtNow, "{y}{m}"),
          mid_table_remark_005: parseTime(dtNow, "{y}"),
          mid_table_remark_004: dtNow.getTime(),
          mid_table_remark_013: 1,
          mid_table_remark_014: 100,
          mid_table_remark_015: 20,
          mid_table_remark_020: -1,
          mid_table_remark_029: 1112,
          mid_table_remark_034: 1,
          mid_table_remark_035: 1,
          mid_table_remark_003: 1,
          // mid_table_remark_001:null
        });
      } else {
        Object.assign(postData, { pre_db_para_id_public_middle_table,time_update:parseTime(dtNow,"{y}-{m}-{d} {h}:{i}:{s}") });
      }
      console.log(postData, "PostData>>>>");

      middleList(this.Qs.stringify(postData)).then(
        (res) => {
          this.isRequesting = false;
          this.$emit("refresh");
          this.$message.success(`${this.showTitle}成功`);
          this.showDialog = false;
        },
        (error) => {
          this.isRequesting = false;
        }
      );
    },
    // 获取所有的课程列表
    getCourseList() {
      return new Promise((resolve, reject) => {
        try {
          courseMiddleList(
            this.Qs.stringify({
              invoke_method: "public_page_4m_shop_goods_list_2_reg",
              filter_type: 1,
              pre_db_spec_buyer_id: 99101,
              "public_goods_supply_4_agent.id_public_goods_supply_4_agent_is_not_null": true,
              pre_db_para_order_by_para:
                "public_goods_info.id_public_goods_info desc",
            })
          ).then(
            (response) => {
              resolve(response.page_content);
            },
            (error) => {
              resolve([]);
            }
          );
        } catch (error) {
          resolve([]);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.wrap-manjian {
  position: relative;
  width: 100%;
  display: flex;
}
</style>
